<template>
  <div id="components-layout-demo-basic">
    <a-layout>
      <a-layout-sider
        style="
          max-width: 260px;
          min-width: 260px;
          width: 260px;
          background-color: #fff;
          border-right: 1px solid #d5d5d5;
        "
        class="siderHeight"
      >
        <div class="components-list">
          <template v-if="basicFields.length">
            <div class="widget-cate">基础字段</div>

            <draggable
              tag="ul"
              v-model="basicComponents"
              v-bind="{
                group: { name: 'people', pull: 'clone', put: false },
                sort: false,
                ghostClass: 'ghost',
              }"
              item-key="type"
              :move="handleMove"
            >
              <template #item="{ element }">
                <li
                  style="float: left; width: 43%"
                  class="form-edit-widget-label"
                  :class="{ 'no-put': element.type == 'divider' }"
                >
                  <a
                    v-if="basicFields.indexOf(element.type) >= 0"
                    style="display: flex; align-items: center"
                  >
                    <vab-icon
                      :icon="element.icon"
                      style="margin-right: 5px"
                    ></vab-icon>
                    <span>{{ element.name }} {{ element.key }}</span>
                  </a>
                </li>
              </template>
            </draggable>
          </template>

          <template v-if="advanceFields.length">
            <div class="widget-cate">高级字段</div>

            <draggable
              tag="ul"
              v-model="advanceComponents"
              v-bind="{
                group: { name: 'people', pull: 'clone', put: false },
                sort: false,
                ghostClass: 'ghost',
              }"
              item-key="type"
              :move="handleMove"
            >
              <template #item="{ element }">
                <li
                  style="float: left; width: 43%"
                  class="form-edit-widget-label"
                  :class="{ 'no-put': element.type == 'divider' }"
                >
                  <a
                    v-if="advanceFields.indexOf(element.type) >= 0"
                    style="display: flex; align-items: center"
                  >
                    <vab-icon
                      :icon="element.icon"
                      style="margin-right: 5px"
                    ></vab-icon>
                    <span>{{ element.name }}</span>
                  </a>
                </li>
              </template>
            </draggable>
          </template>

          <template v-if="layoutFields.length">
            <div class="widget-cate">布局字段</div>
            <draggable
              tag="ul"
              v-model="layoutComponents"
              v-bind="{
                group: { name: 'people', pull: 'clone', put: false },
                sort: false,
                ghostClass: 'ghost',
              }"
              item-key="type"
              :move="handleMove"
            >
              <template #item="{ element }">
                <li
                  style="float: left; width: 43%"
                  class="form-edit-widget-label"
                  :class="{ 'no-put': element.type == 'divider' }"
                >
                  <a
                    v-if="layoutFields.indexOf(element.type) >= 0"
                    style="display: flex; align-items: center"
                  >
                    <vab-icon
                      :icon="element.icon"
                      style="margin-right: 5px"
                    ></vab-icon>
                    <span>{{ element.name }}</span>
                  </a>
                </li>
              </template>
            </draggable>
          </template>
        </div>
      </a-layout-sider>
      <a-layout style="background-color: #fff; padding-left: 10px">
        <div style="margin-bottom: 10px; text-align: left">
          <a-button
            v-if="preview"
            class="ml-1"
            type="primary"
            @click="handlePreview"
          >
            <template #icon><EyeOutlined /></template>
            预览
          </a-button>
          <a-button
            v-if="saveForm"
            class="ml-1"
            type="primary"
            @click="handleSaveForm"
          >
            <template #icon><BookOutlined /></template>
            保存表单
          </a-button>

          <a-button
            class="ml-1"
            type="primary"
            @click="formSettingVisible = true"
          >
            <template #icon><SettingOutlined /></template>
            表单属性
          </a-button>
        </div>
        <a-divider style="margin: 10px 0"></a-divider>
        <a-layout-content>
          <widget-form
            ref="widgetForm"
            v-if="!resetForm"
            :widgetForm="widgetForm"
            @changeSelect="changeSelect"
            @openSetting="openSetting"
          ></widget-form>
        </a-layout-content>
      </a-layout>
      <vxe-modal
        resize
        width="860"
        title="表单设置"
        v-model="formSettingVisible"
      >
        <!-- 表单配置 -->
        <form-config :dataAfferent="widgetForm.config"></form-config>
      </vxe-modal>
      <vxe-modal resize width="860" title="字段配置" v-model="settingVisible">
        <template v-slot>
          <widget-config
            :key="widgetConfigKey"
            v-if="!resetForm"
            :formData="widgetForm.config"
            :dataAfferent="widgetFormSelect"
          ></widget-config>
        </template>
      </vxe-modal>
    </a-layout>

    <!-- 自定义表单预览开始 -->
    <vxe-modal
      width="900"
      title="自定义报表"
      v-model="previewVisible"
      show-zoom
      resize
    >
      <template v-slot>
        <!-- 生成自定义表单 -->
        <generate-form
          insite="true"
          v-if="previewVisible"
          :data="widgetForm"
          ref="generateForm"
          :flowData="flowData"
        ></generate-form>
        <div style="text-align: center" class="mt-1">
          <a-button type="primary" @click="handleTest">
            <template #icon><BlockOutlined /></template>
            获取数据
          </a-button>
          <a-button @click="previewVisible = false" class="ml-1">
            <template #icon><CloseCircleOutlined /></template>
            取消
          </a-button>
        </div>
      </template>
    </vxe-modal>
    <!-- 自定义表单预览结束 -->
  </div>
</template>

<script>
  import VabIcon from '@/layout/vab-icon'
  import draggable from 'vuedraggable'
  import WidgetConfig from './WidgetConfig'
  import FormConfig from './FormConfig'
  import WidgetForm from './WidgetForm'
  import GenerateForm from './GenerateForm'
  import {
    basicComponents,
    layoutComponents,
    advanceComponents,
  } from './componentsConfig.js'

  import { Add, Get, Update } from '@/api/form/api'
  import {
    EyeOutlined,
    BookOutlined,
    SettingOutlined,
    BlockOutlined,
    CloseCircleOutlined,
  } from '@ant-design/icons-vue'
  export default {
    name: 'FmMakingReport',
    components: {
      draggable,
      WidgetConfig,
      FormConfig,
      WidgetForm,
      GenerateForm,
      EyeOutlined,
      BookOutlined,
      SettingOutlined,
      BlockOutlined,
      CloseCircleOutlined,
      VabIcon,
    },
    props: {
      clearForm: {
        type: Boolean,
        default: false,
      },

      preview: {
        type: Boolean,
        default: false,
      },
      saveForm: {
        type: Boolean,
        default: false,
      },
      generateCode: {
        type: Boolean,
        default: false,
      },

      // 基础字段（自定义的组件要在这添加）
      basicFields: {
        type: Array,
        default: () => [
          'alert',
          'input',
          'textarea',
          'number',
          'radio',
          'checkbox',
          'time',
          'date',
          'rate',
          'color',
          'select',
          'switch',
          'slider',
          'text',
        ],
      },
      // 高级字段
      advanceFields: {
        type: Array,
        default: () => [
          'table',
          'imgupload',
          'fileupload',
          'editor',
          'cascader',
        ],
      },
      // 布局字段
      layoutFields: {
        type: Array,
        default: () => ['grid'],
      },
    },

    data() {
      return {
        widgetConfigKey: '', //widget-config key值（用于刷新组件）
        resetForm: true, //数据请求完成后加载
        flowData: {}, //初始表单数据
        basicComponents, // 基础字段
        layoutComponents, // 布局字段
        advanceComponents, // 高级字段
        // 初始表单配置
        widgetForm: {
          list: [],
          config: {
            labelWidth: 100, //标签宽度px
            labelPosition: 'right', // 标签对其方式
            size: 65, //内容宽度 %
            tableName: '',
            note: '',
          },
        },
        widgetFormSelect: null, // 选择的组件数组
        previewVisible: false, // 表单预览
        htmlTemplate: '', // 生成的html表单代码
        vueTemplate: '', // 生成的vue表单代码
        settingVisible: false,
        formSettingVisible: false,
      }
    },
    computed: {
      dragOptions() {
        return {
          animation: 200,
          group: 'description',
          disabled: false,
          ghostClass: 'ghost',
        }
      },
    },
    created() {
      if (this.$route.query.id === undefined) {
        this.resetForm = false
      } else {
        Get({ id: this.$route.query.id }).then((res) => {
          if (res.isSuccess) {
            this.widgetForm = JSON.parse(res.content.content)
            this.resetForm = false
          }
        })
      }
    },
    methods: {
      openSetting() {
        this.settingVisible = true
        this.widgetConfigKey = new Date().getTime()
      },
      changeSelect(val) {
        this.widgetFormSelect = val
      },
      handleMove() {
        return true
      },
      handlePreview() {
        // console.log(this.widgetForm)
        this.previewVisible = true
      },
      handleTest() {
        // console.log('data:', this.$refs.generateForm.data)
        this.$refs.generateForm
          .getData()
          .then((data) => {
            console.log(data)
          })
          .catch((e) => {
            console.log(e)
            this.$refs.widgetPreview.end()
          })
      },

      // 保存表单
      handleSaveForm() {
        var that = this
        this.$confirm({
          title: '确定要生成表单？',
          content: '点击确定提交至数据库。',
          okText: '是',
          cancelText: '否',
          onOk() {
            console.log('thatw.idgetForm', that.widgetForm)
            var isSubmit = true
            that.widgetForm.list.forEach((element) => {
              if (element.type === 'grid') {
                element.columns.forEach((child) => {
                  child.list.forEach((childItem) => {
                    if (childItem.field === undefined) {
                      isSubmit = false
                    }
                  })
                })
              } else if (element.field === undefined) {
                isSubmit = false
              }
            })

            var config = that.widgetForm.config
            if (
              config.tableName === undefined ||
              config.formtype === undefined ||
              config.linkDb == undefined ||
              config.linktable == undefined ||
              config.primarykey == undefined ||
              config.titleFiled == undefined
            ) {
              isSubmit = false
            }
            if (isSubmit) {
              if (that.$route.query.id === undefined) {
                Add({
                  DictId: that.widgetForm.config.reportType,
                  Name: that.widgetForm.config.reportName,
                  DbId: that.widgetForm.config.linkDb,
                  Json: JSON.stringify(that.widgetForm),
                  Note: that.widgetForm.config.note,
                }).then((res) => {
                  console.log(res)
                  that.$message.success('提交成功！')
                })
              } else {
                Update(
                  { id: that.$route.query.id },
                  {
                    DictId: that.widgetForm.config.reportType,
                    Name: that.widgetForm.config.reportName,
                    DbId: that.widgetForm.config.linkDb,
                    Json: JSON.stringify(that.widgetForm),
                    Note: that.widgetForm.config.note,
                  }
                ).then((res) => {
                  console.log(res)
                  that.$message.success('修改成功！')
                })
              }
            } else {
              that.$message.error('表单属性或组件字段不能为空')
            }

            // 、、-------------------------------------------------
          },
        })
      },
    },
  }
</script>

<style lang="less">
  .siderHeight {
    height: calc(100vh - 200px);
  }

  .form-edit-widget-label {
    font-size: 12px;
    display: block;
    width: 48%;
    line-height: 26px;
    position: relative;
    float: left;
    left: 0;
    overflow: hidden;

    margin: 1%;
    margin-right: 10px;
    color: #333;
    border: 1px solid #f4f6fc;
  }

  .form-edit-widget-label > a {
    display: block;
    cursor: move;
    background: #f4f6fc;
    border: 1px solid #f4f6fc;
    color: black;
  }
  .form-edit-widget-label > a .icon {
    margin-right: 6px;
    margin-left: 8px;
    font-size: 14px;
    display: inline-block;
    vertical-align: middle;
  }

  .components-list ul {
    position: relative;
    overflow: hidden;
    padding: 0 10px 10px;
    margin: 0;
  }

  .widget-cate {
    padding: 8px 12px;
    font-size: 13px;
  }

  /* --------------- */
</style>
